package com.yadong.smarthome2.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputType;
import android.widget.EditText;

import com.yadong.smarthome2.protocol2.RequestProtocol.Parameter;
import com.yadong.smarthome2.protocol2.ResultProtocol.Function.Argument;

public class InputParameterDialogBuilder {
    private Context mContext;
    private List<Parameter> mParameters = new ArrayList<Parameter>();

    public InputParameterDialogBuilder(Context context) {
        this.mContext = context;
    }

    public List<Parameter> getAllParameters() {
        return mParameters;
    }

    public Dialog createInputDailog(final List<Argument> arguments) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("请输入参数");
        String message = "总共:" + arguments.size() + "个参数, 参数之间用逗号隔开.";
        for (int i = 0; i < arguments.size(); i++) {
            Argument argument = arguments.get(i);
            message += "\n第" + (i + 1) + "个参数:";
            message += "类型是:" + argument.getType();
            if (argument.getLimit().startsWith("o")) {
                message += "请输入" + argument.getLimit().substring(1) + "中的一个";
            } else if (argument.getLimit().startsWith("r")) {
                message += "请输入范围为" + argument.getLimit().substring(1) + "的数据";
            }
        }
        builder.setMessage(message);

        // Set up the input
        final EditText input = new EditText(mContext);
        // Specify the type of input expected; this, for example, sets the input as a password, and
        // will mask the text
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);

        // Set up the buttons
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String text = input.getText().toString();
                String[] items = text.split(",");
                mParameters = new ArrayList<Parameter>();
                Parameter.Builder parameterBuilder = Parameter.newBuilder();
                for (int i = 0; i < arguments.size(); i++) {
                    Argument argument = arguments.get(i);
                    parameterBuilder.clear();
                    parameterBuilder.setCommnd(argument.getName());
                    parameterBuilder.setArgs(items[i]);
                    mParameters.add(parameterBuilder.build());
                }
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        return builder.create();
    }
}
